using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVC.Models
{
    public class SessionCustomerRepository
    {
        /// <summary>
        /// Attempts to grab the current list of EditableCustomers from Session. If the Session variable is null it will
        /// go to our underlying datasource and create a list of EditableCustomer
        /// </summary>
        /// <returns>List of EditableCustomer</returns>
        public static IList<EditableCustomer> CustomerList()
        {
            IList<EditableCustomer> result = (IList<EditableCustomer>)HttpContext.Current.Session["Customers"];

            if (result == null)
            {
                HttpContext.Current.Session["Customers"] = result =
                    (from customers in new NorthwindEntityDiagrams().Customers
                     select new EditableCustomer
                     {
                         CustomerID = customers.CustomerID,
                         CompanyName = customers.CompanyName,
                         Address = customers.Address,
                         City = customers.City,
                         Country = customers.Country
                     }).ToList();
            }

            return result;
        }

        //Selects a single EditableCustomer
        public static EditableCustomer SelectOne(Func<EditableCustomer, bool> predicate)
        {
            return CustomerList().Where(predicate).FirstOrDefault();
        }
        
        //Insert a new EditableCustomer in our list
        public static void Insert(EditableCustomer customer)
        {
            customer.CustomerID = Guid.NewGuid().ToString();
            CustomerList().Insert(0, customer);
        }

        //Update the current EditableCustomer in our list
        public static void Update(EditableCustomer customer)
        {
            //find the EditableCustomer in question
            EditableCustomer targetCustomer = SelectOne(c => c.CustomerID == customer.CustomerID);

            if (targetCustomer != null)
            {
                targetCustomer.CompanyName = customer.CompanyName;
                targetCustomer.Address = customer.Address;
                targetCustomer.City = customer.City;
                targetCustomer.Country = customer.Country;
            }
        }

        //Delete the current EditableCustomer from our list
        public static void Delete(EditableCustomer customer)
        {
            //find the EditableCustomer in question
            EditableCustomer targetCustomer = SelectOne(c => c.CustomerID == customer.CustomerID);

            if (targetCustomer != null)
            {
                CustomerList().Remove(targetCustomer);
            }
        }
    }
}